from quant_researcher.quant.project_tool.time_tool import get_yesterday, date_shifter
from quant_researcher.quant.datasource_fetch.crypto_api.coinmarketcap import get_asset_ohlcvm_via_http

import os
from utils import df_into_db
import pandas as pd
import time

DATA_DIR = f'E:\\指标数据'
data_source = "coinmarketcap"
start_date = '2013-01-01'
end_date = get_yesterday(marker='with_n_dash')  # 计算截止昨日收盘
file_path = os.path.join(DATA_DIR, f'all_history_ohlcvm_{data_source}')
file_name = os.path.join(file_path, f'stablecoin_{data_source}')


true_stalecoin_crypto = {'usdt': 'tether',
                         'usdc': 'usd-coin',
                         'busd': 'binance-usd',
                         'tusd': 'trueusd',
                         'usdp': 'paxos-standard',
                         'husd': 'husd',
                         'gusd': 'gemini-dollar',
                        #  'usdk': 'usdk',
                         }

update = True
all_recent_data_list = []
asset_df_list = []
for asset in true_stalecoin_crypto.keys():
    if update:
        asset_history_data = pd.read_excel(f'{file_name}.xlsx', sheet_name=asset)
        asset_history_data['end_date'] = pd.to_datetime(asset_history_data['end_date'])
        asset_history_data['end_date'] = asset_history_data['end_date'].dt.strftime('%Y-%m-%d')
        asset_history_data.set_index('end_date', inplace=True)

        if data_source == 'coinmarketcap':
            recent_data = get_asset_ohlcvm_via_http(asset=true_stalecoin_crypto[asset], range='1Y')
        elif data_source == 'coingecko':
            raise NotImplementedError

        next_date = date_shifter(asset_history_data.index[-1], step='days', how_many=1)
        if recent_data is not None:
            asset_df = pd.concat([asset_history_data.iloc[:, ], recent_data.loc[next_date:, ]])
        else:
            asset_df = asset_history_data.copy()
            recent_data = asset_history_data.copy()

        asset_df = pd.concat([asset_history_data.iloc[:, ], recent_data.loc[next_date:, ]])
        asset_df = asset_df[asset_history_data.columns]
        asset_df.sort_index(inplace=True)
        asset_df.index.name = 'end_date'

    else:  # 重算全部历史数据
        if data_source == 'coingecko':
            raise NotImplementedError
        else:
            raise NotImplementedError
    all_recent_data_list.append(asset_df['market_cap'].rename(asset))
    asset_df['symbol'] = asset
    asset_df = asset_df.reset_index(drop=False)
    asset_df.fillna(0, inplace=True)
    df_into_db(asset_df, db_name="all_history_ohlcvm_coinmarketcap", table_name="stablecoin_coinmarketcap")
    time.sleep(5)  # 避免读取太频繁

all_data_df = pd.concat(all_recent_data_list, axis=1)
all_data_df['market_cap'] = all_data_df.sum(axis=1)
all_data_df["symbol"] = "stablecoin_sum"
all_data_df = all_data_df.reset_index(drop=False)
columns = ['end_date', 'symbol','market_cap']
df_into_db(all_data_df[columns], db_name="all_history_ohlcvm_coinmarketcap", table_name="stablecoin_coinmarketcap")
print("stop")

